<template>
  <div class="content">
    <a-page-header
        :title="'ID-' + matchId"
        :subtitle="matchInfo.matchTitle"
        :show-back="false"
    >
      <template #breadcrumb>
        <a-breadcrumb>
          <a-breadcrumb-item>首页</a-breadcrumb-item>
          <a-breadcrumb-item>比赛</a-breadcrumb-item>
          <a-breadcrumb-item>比赛详情</a-breadcrumb-item>
        </a-breadcrumb>
      </template>
      <template #extra>
        <a-space>
          <div >
            <a-space>
              <span>距离比赛结束还有</span>
              <a-countdown
                  style="color: red !important;margin-right: 20px"
                  :value="Date.parse(matchInfo.endTime)"
                  :now="now"
                  @finish="getMatchInfo"
              />
            </a-space>
          </div>
          <a-button
              :disabled="getTimeStatus(matchInfo) !== 0"
              v-if="signInfo !== null"
              type="primary"
              status='danger'
              @click="cancelSign"
          >
            <template #icon>
              <icon-sync/>
            </template>
            取消报名
          </a-button>
          <a-button
              :disabled="getTimeStatus(matchInfo) !== 0"
              v-if="signInfo === null"
              type="primary"
              @click="sign"
              style="width: 100px;">
            <template #icon>
              <icon-send/>
            </template>
            报名
          </a-button>
        </a-space>
      </template>
    </a-page-header>
    <a-descriptions
        style="margin-top: 20px;margin-left: 20px"
        :data="[
                {
                  label: '主办方',
                  value: matchInfo.matchHost
                },
                {
                  label: '比赛类型',
                  value: matchInfo.matchType == 0 ? '个人赛' : '团队赛'
                },
                {
                  label: '比赛简介',
                  value: matchInfo.intro
                },
                {
                  label: '开始时间',
                  value: matchInfo.startTime
                },
                {
                  label: '结束时间',
                  value: matchInfo.endTime
                },
                {
                  label: '比赛提示',
                  value: matchInfo.matchTip
                }
            ]"
        :column="3"
        size="large"
    >
    </a-descriptions>
    <a-tabs default-active-key="1">
      <a-tab-pane key="1" title="比赛题目">
        <a-row :gutter="16" v-if="userRole === 'admin'">
          <a-col :span="6">
            <a-select
                style="margin-bottom: 15px"
                placeholder="请选择题目"
                @search="getTopicList"
                v-model="topicsId"
                allow-clear
                :filter-option="false">
              <a-option v-for="item of topics" :key="item.id" :value="item.id">{{item.title}}</a-option>
            </a-select>
          </a-col>
          <a-col :span="18">
            <a-button
                type="primary"
                style="margin-bottom: 15px"
                :disabled="topicsId == null || topicsId == ''"
                @click="bindTopic"
            >
              添加题目
            </a-button>
            <a-space>
              <a-button
                  status="success"
                  style="margin-bottom: 15px;margin-left: 640px"
                  :disabled="getTimeStatus(matchInfo) !== 2"
                  @click="goToTopicJudge()"
              >
                前往判题
              </a-button>
              <a-button
                  status="warning"
                  @click="updateExp"
                  style="margin-bottom: 15px"
                  :disabled="getTimeStatus(matchInfo) !== 2"
              >
                一键结算
              </a-button>
            </a-space>
          </a-col>
        </a-row>
        <a-table :columns="matchTopicListColumns" :data="matchTopicListData">
          <template #id="{ record }">
            <a-link @click="goToTopic(record.id)" :disabled="getTimeStatus(matchInfo) !== 1">{{ record.id }}</a-link>
          </template>
          <template #tags="{ record }">
            <a-space wrap>
              <a-tag v-for="(tag, index) of JSON.parse(record.tags)" :key="index" color="green"
              >{{ tag }}
              </a-tag>
            </a-space>
          </template>
          <template #submitStatus="{ record }">
            <icon-check v-if="record.submitStatus === true" style="color: green" />
          </template>
          <template #difficulty="{ record }">
            <a-rate :default-value="record.difficulty" readonly/>
          </template>
          <template #operate="{ record }">
            <a-space>
              <a-button  v-if="userRole === 'admin'" type="primary" status="danger" @click="unBindTopic(record)">删除</a-button>
            </a-space>
          </template>
        </a-table>
      </a-tab-pane>
      <a-tab-pane key="2" title="报名列表">
        <a-table :columns="matchSignListColumns" :data="matchSignListData">
          <template #operate="{ record }">
            <a-button  v-if="userRole === 'admin'" type="primary" @click="removeSign(record)">取消报名</a-button>
          </template>
        </a-table>
      </a-tab-pane>
      <a-tab-pane key="3" title="排行榜" :disabled="getTimeStatus(matchInfo) !== 2">
        <a-table :columns="rankingColumns" :data="matchSignListData" v-if="matchSubmitStatus === true">
          <template #ranking="{record}">
            <a-image width="30" height="30" v-if="record.index == 1" src="https://static.shiyanlou.com/lanqiao/frontend/dist/img/p-medal-1.465632f.png"></a-image>
            <a-image width="30" height="30" v-if="record.index == 2" src="https://static.shiyanlou.com/lanqiao/frontend/dist/img/p-medal-2.b7a14ad.png"></a-image>
            <a-image width="30" height="30" v-if="record.index == 3" src="https://static.shiyanlou.com/lanqiao/frontend/dist/img/p-medal-3.0ce2247.png"></a-image>
            <div v-if="record.index > 3">
              {{record.index}}
            </div>
          </template>
        </a-table>
        <a-result v-else status="warning" title="排行榜暂未开放">
          <template #subtitle>
            等待管理员判题完成后结算成绩，排行榜才可查看
          </template>

          <template #extra>
            <a-space>
              <a-button type='primary'>知道了</a-button>
            </a-space>
          </template>
        </a-result>
      </a-tab-pane>
    </a-tabs>
  </div>
</template>

<script setup lang="ts">
import { onMounted, ref} from "vue";
import {useRouter} from "vue-router";
import request from "../../axios/axios.ts";
import useUserInfoStore from "../../store/user.ts";
import {Message} from "@arco-design/web-vue";

const router = useRouter();
// 获取路由中携带的比赛参数
const matchId = router.currentRoute.value.query.id

interface topicsType {
  id: number,
  title: string,
}

const topics = ref<Array<topicsType>>([])
const topicsId = ref()

const matchInfo = ref({})
const signInfo = ref({})
const matchTopicListColumns = [
  {
    title: '序号',
    dataIndex: 'index'
  },
  {
    title: '提交',
    slotName: 'submitStatus',
  },
  {
    title: '题号',
    slotName: 'id',
  },
  {
    title: '题目名称',
    dataIndex: 'title',
  },
  {
    title: '标签',
    slotName: 'tags'
  },
  {
    title: '经验值',
    dataIndex: 'topicExp',
    sortable: {
      sortDirections: ['ascend', 'descend']
    }
  },
  {
    title: '题目难度',
    slotName: 'difficulty',
  },
  {
    title: '创建时间',
    dataIndex: 'createTime'
  },
  {
    title: '操作',
    slotName: 'operate'
  }
]

const matchSignListColumns = [
  {
    title: '序号',
    dataIndex: 'index'
  },
  {
    title: '用户id',
    dataIndex: 'user.id',
  },
  {
    title: '用户名称',
    dataIndex: 'user.userName',
  },
  {
    title: '用户账号',
    dataIndex: 'user.userAccount',
  },
  {
    title: '创建时间',
    dataIndex: 'createTime'
  },
  {
    title: '操作',
    slotName: 'operate'
  }
]

const rankingColumns = [
  {
    title: '排行',
    slotName:'ranking'
  },
  {
    title: '用户id',
    dataIndex: 'user.id',
  },
  {
    title: '用户名称',
    dataIndex: 'user.userName',
  },
  {
    title: '用户账号',
    dataIndex: 'user.userAccount',
  },
  {
    title: '总经验值',
    dataIndex: 'signExp',
  },
  {
    title: '创建时间',
    dataIndex: 'createTime'
  }
]
const matchSubmitStatus = ref(false)
const matchTopicListData = ref([])
const matchSignListData = ref([])
const now = new Date()

onMounted(() => {
  getMatchInfo()
  getSignInfo()
  getTopicList()
  getMatchSubmitStatus()
})
const user = useUserInfoStore()
const {id, userRole} = user.userInfo
// 获取比赛信息
const getMatchInfo = () => {
  request.get("/api/match/query/" + matchId).then(res => {
    if (res.data.success) {
      matchInfo.value = res.data.data
      matchTopicListData.value = res.data.data.matchTopicList
      matchTopicListData.value.forEach((item,index) =>{
        item.index = index + 1
      })
      matchSignListData.value = res.data.data.matchSignList
      matchSignListData.value.forEach((item,index) =>{
        item.index = index + 1
      })
    }
  })
}

const getSignInfo = () => {
  request.post("/api/sign/isSign", {
    matchId: matchId,
    userId: id
  }).then(res => {
    if (res.data.success) {
      signInfo.value = res.data.data
    }
  })
}

const getTimeStatus = (item) => {
  const nowTime = new Date().getTime()
  const startTime = new Date(item.startTime).getTime()
  const endTime = new Date(item.endTime).getTime()
  if (nowTime < startTime) {
    return 0 // 未开始
  } else if (nowTime > startTime && nowTime < endTime) {
    return 1 // 进行中
  } else {
    return 2 // 已结束
  }
}

// 取消报名
const removeSign = (item) => {
  request.delete("/api/sign/delete", {
    params: {
      id:item.id
    }
  }).then(res => {
    if (res.data.success) {
     Message.success("取消报名成功")
      getMatchInfo()
      getSignInfo()
    }
  })
}
const cancelSign=()=> {
  request.delete("/api/sign/delete",{
    params:{
      id:signInfo.value.id
    }
  }).then(res => {
    if (res.data.success) {
      Message.success("取消报名成功")
      getMatchInfo()
      getSignInfo()
    }
  })
}
// 报名
const sign = () => {
  request.post("/api/sign/sign", {
    matchId: matchInfo.value.id,
    userId: id
  }).then(res => {
    if (res.data.success) {
      Message.success("报名成功")
      getMatchInfo()
      getSignInfo()
    }
  })
}


const getTopicList = (value: string) => {
  request.get("/api/topic/query/list", {
    params: {
      topicName: value || " "
    }
  }).then(res => {
    if (res.data.success) {
      topics.value = res.data.data
    }
  })
}

const bindTopic = () => {
  request.post("/api/topic/bind", {
    bind: true,
    matchId: matchId,
    topicId: topicsId.value
  }).then(res => {
    if (res.data.success) {
      Message.success("绑定成功")
      topicsId.value = null
      getMatchInfo()
    }
  })
}

const unBindTopic = (topic: number) => {
  request.post("/api/topic/bind", {
    bind: false,
    matchId: matchId,
    topicId: topic.id
  }).then(res => {
    if (res.data.success) {
      Message.success("删除成功")
      getMatchInfo()
    }
  })
}

const getMatchSubmitStatus = () => {
  request.get("/api/match/isMatchFinish",{
    params: {
      matchId: matchId
    }
  }).then(res => {
    if (res.data.success){
      matchSubmitStatus.value = res.data.data
    }
  })
}

const updateExp = () => {
  request.get("/api/submit/updateAllUserExpToSign",{
    params: {
      matchId: matchId
    }
  }).then(res => {
    if (res.data.success){
      Message.success("结算成功！请稍后查看排行榜")
      getMatchInfo()
    }
  })
}






const goToTopic = (topicId: number) => {
  // 判断当前登录角色是否是管理员  再判断当前登录角色是否报名
  if(userRole !== 'admin' && signInfo.value === null){
    Message.error("当前用户未报名,不能查看")
    return
  }

  router.push("/match/topic?matchId=" + matchId + "&topicId=" + topicId)
}

const goToTopicJudge = () => {
  router.push("/topic/judge?matchId=" + matchId)
}
</script>


<style scoped>
.content {
  padding: 20px;
  width: 80%;
  margin: 0 auto;
}
</style>
